package com.yjtc.cbg.commonutildemo.View;

import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.yjtc.cbg.commonutildemo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Title: CommonUtilDemo
 * <p/>
 * Description:利用RxBinding和RxJava实现倒计时按钮，防抖效果和搜索实现
 * <p/>
 * Author:baigege (baigegechen@gmail.com)
 * <p/>
 * Date:2017-06-09
 */
public class RxBindingActivity extends BaseActivity {

    private Button mButton;
    private EditText mEditText;
    private Button smsButton;

    //设置总倒计时时间数
    private int count = 60 * 1000;
    //    设置是假间隔数
    private int interval = 1000;

    private CountTimer mTimer;

    @Override
    public int getContentVIew() {
        return R.layout.layout_binding;
    }

    @Override
    public void initData() {
        mButton = (Button) findViewById(R.id.button);
        mEditText = (EditText) findViewById(R.id.editText);
        smsButton = (Button) findViewById(R.id.smsButton);
        mTimer = new CountTimer(count, interval);
        RxView.clicks(mButton).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                //do sth  在一段时间内多次点击，只处理这段时间内的第一次点击事件
                //如果为防止多次点击按钮而带来的不必要开销，可以在这里对事件进行处理
                System.out.println(System.currentTimeMillis());
            }
        });

        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //do sth  在这里进行关键字，词的查询操作
                // 这里模拟数据请求，返回list数据
                List<String> mDatas = new ArrayList<String>();
                mDatas.add("哈哈哈哈");
                mDatas.add("呵呵呵呵");
                System.out.println("------------当前时间:" + System.currentTimeMillis() + "---------------");
                for (String str : mDatas) {
                    System.out.println(str);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        RxTextView.textChanges(mEditText).debounce(300, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())//对text的坚挺必须在ui线程中
                .filter(new Func1<CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence charSequence) {
                        return charSequence.toString().length() > 0;
                    }
                }).map(new Func1<CharSequence, String>() {
            @Override
            public String call(CharSequence charSequence) {
                if (null != charSequence && !"".equals(charSequence.toString().trim()))
                    return charSequence.toString().trim();
                return null;
            }
        }).observeOn(Schedulers.io()).switchMap(new Func1<String, Observable<List<String>>>() {
            //switchMap操作符：指发射最近的一个
            @Override
            public Observable<List<String>> call(String s) {
                //do sth  在这里通过keywords关键字进行网络请求，获取改关键字搜索到的记录
                // 这里模拟数据请求，返回list数据
                List<String> mDatas = new ArrayList<String>();
                mDatas.add("哈哈哈哈");
                mDatas.add("呵呵呵呵");
                return Observable.just(mDatas);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<String>>() {
            @Override
            public void call(List<String> strings) {
                System.out.println("------------当前时间:" + System.currentTimeMillis() + "---------------");
                for (String s : strings) {
                    System.out.println(s);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                //处理出错的逻辑

            }
        });

        smsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                smsButton.setEnabled(false);
                mTimer.start();
            }
        });

        smsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //总倒计时秒数
                final int count = 60;
                //每1秒发射一次数据
                Observable.interval(0, 1, TimeUnit.SECONDS).take(count)
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                //在数据孩子啊发射期间设置按钮不可点击
                                smsButton.setEnabled(false);
                            }
                        }).map(new Func1<Long, String>() {
                    @Override
                    public String call(Long integer) {
                        //对发射过来的int类型数据进行转换，便于ui显示
                        return String.valueOf(count - integer);
                    }
                }).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
                        //当数据发射完成（即60秒后），设置按钮可点击
                        smsButton.setEnabled(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //错误处理逻辑
                    }

                    @Override
                    public void onNext(String s) {
                    //在这里接受发射过来的字符串数据，用于ui显示
                        smsButton.setText("剩余" + s + "秒");
                    }
                });
            }
        });
    }

    class CountTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            smsButton.setText("剩余" + millisUntilFinished / interval + "秒");
        }

        @Override
        public void onFinish() {
            smsButton.setEnabled(true);
        }
    }
}
